package com.ttbj.controller.ytpay;

import java.io.File;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ttbj.api.dto.Page;
import com.ttbj.api.dto.YtPayDto;
import com.ttbj.api.exception.BusinessException;
import com.ttbj.api.yitong.YtPayService;
import com.ttbj.core.util.FileUtil;
import com.ttbj.util.ViewDataUtil;


@Controller
public class YtPayController {
	
	@Autowired
	private YtPayService ytPayService;
	
	/**
	 * 易通金服支付信息列表
	 * @return
	 */
	@RequestMapping("/ytpay/payinfo_list.htm")
	public String payinfo_list() {
		return "ytpay/payinfo_list";
	}
	
	/**
	 * 分页条件查询支付详情列表
	 * @param request
	 * @param startDateTime 支付时间的开始时间 
	 * @param endDateTime 支付时间的结束时间
	 * @param merOrderNum 商户订单号
	 * @param page 分页页码
	 * @return
	 */
	@RequestMapping(value="/ytpay/getYtPayInfoByPage.htm", method=RequestMethod.POST, produces={"text/html;charset=UTF-8;","application/json;"})
	@ResponseBody
	public String getYtPayInfoByPage(HttpServletRequest request, @RequestParam(required=false) String startDateTime,
									 @RequestParam(required=false) String endDateTime,
									 @RequestParam(required=false) String merOrderNum, 
									 @RequestParam(required=false) String orderId, Page page) {
		try {
			List<YtPayDto> ytPayDtos = this.ytPayService.findYtPayInfoByPage(startDateTime, endDateTime, merOrderNum, orderId, page);
			int count = 0;
			if (null != ytPayDtos) {
				count = this.ytPayService.findYtPayInfoByPageCount(startDateTime, endDateTime, merOrderNum, orderId);
			}
			return ViewDataUtil.buildSuccessPageJson("支付列表", ytPayDtos, count);
		} catch (BusinessException e) {
			return ViewDataUtil.buildFailureJson(e.getErrorCode(), e.getMessage());
		}
	}
	
	/**
	 * 对账文件下载
	 * @param request 
	 * @param type 类型：1主扫（微信/支付宝），2被扫（微信小程序）
	 * @param tranDate 清算日期：如 2018-10-25
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/ytpay/exportTradeFile.htm")
	public ResponseEntity<byte[]> exportTradeFile(HttpServletRequest request, @RequestParam Integer type, @RequestParam String tranDate) throws Exception{
		//调用对账文件下载接口
		Map<String, String> resultMap = this.ytPayService.loadTradeFile(type, tranDate);
		String respCode = resultMap.get("respCode");	//获取响应码，除了0000以外都是失败
		if (respCode.equals("0000")) {
			HttpHeaders headers = new HttpHeaders(); 
			File file = new File(request.getContextPath() + "/WEB-INF/file/tradeFile.txt");
			//将响应的文件内容（content）写入到tradeFile.txt中
			FileUtil.writeFile(resultMap.get("content"), file);
			headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
			//设置文件类型
			headers.setContentDispositionFormData("attachment", resultMap.get("fileName"));
			return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), headers, HttpStatus.CREATED);
		}else {
			return new ResponseEntity<byte[]>(resultMap.get("respMsg").getBytes(), HttpStatus.CREATED);
		}
	}
}
